package practiceTest.chap03.work1.BubbleSort;

/**
 * Created by root on 2017/7/12.
 */
public class ArrayBub{
    private long[] a;
    private int nElems;

    public ArrayBub(int max){
        a = new long[max];
        nElems = 0;
    }

    public void insert(long value){
        a[nElems] = value;
        nElems++;
    }

    public void display(){
        for (int j=0; j<nElems; j++) {
            System.out.print(a[j] + "  ");
        }
        System.out.println();
    }

    public void bubbleSort() {
        int outer, inner;
        for (outer=nElems-1; outer>0; outer--) {
            for (inner=0; inner<outer; inner++) {
                if (a[inner] > a[inner+1]) {
                    swap(inner, inner+1);
                }
            }
        }
    }

    public void swap(int one, int two) {
        long temp = a[two];
        a[two] = a[one];
        a[one] = temp;
    }

    /**
     * 用左右指针的思想，代码可读性强
     */
    public void dubblyBubbleSort() {
        int leftout=0, rightout=nElems-1, in;//leftout,rightout为左右两端的指针
        for (; leftout<rightout; leftout++, rightout--) {
            for (in = leftout; in<rightout; in++) {
                if (a[in] > a[in+1]) {
                    swap(in, in+1);
                }
            }
            for (in=rightout-1; in>leftout; in--) {
                if (a[in-1] > a[in]) {
                    swap(in-1,in);
                }
            }
        }
    }



}
